/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.actionPage;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.util.Folder;
import com.blandware.atleap.common.util.FolderList;
import com.blandware.atleap.common.util.PartialCollection;
import com.blandware.atleap.common.util.QueryInfo;
import com.blandware.atleap.common.util.RegExUtil;
import com.blandware.atleap.model.core.ActionPage;
import com.blandware.atleap.service.core.PageManager;
import com.blandware.atleap.webapp.action.core.grid.BaseGridAction;
import com.blandware.atleap.webapp.taglib.core.grid.util.FilterConditions;
import com.blandware.atleap.webapp.taglib.core.grid.util.Grid;
import com.blandware.atleap.webapp.taglib.core.grid.util.StringFilter;
import com.blandware.atleap.webapp.util.core.VirtualFolder;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * <p>Forward to the page with list of action pages
 * </p>
 * <p><a href="ListActionPagesAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.28 $ $Date: 2007/12/18 18:14:37 $
 * @struts.action path="/core/actionPage/list"
 * name="actionPageForm"
 * validate="false"
 * roles="core-actionPage-list"
 * @struts.action-forward name="listActionPages"
 * path=".core.actionPage.list"
 */
public final class ListActionPagesAction extends BaseGridAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		String currentFolder = "";
		if ( request.getParameter("currentFolder") != null ) {
			currentFolder = request.getParameter("currentFolder");
			request.getSession().setAttribute(WebappConstants.ACTION_PAGES_CURRENT_PATH_KEY, currentFolder);
		} else if ( request.getSession().getAttribute(WebappConstants.ACTION_PAGES_CURRENT_PATH_KEY) != null ) {
			currentFolder = (String) request.getSession().getAttribute(WebappConstants.ACTION_PAGES_CURRENT_PATH_KEY);
		}

		if ( currentFolder == null || currentFolder.equals("/") ) {
			currentFolder = "";
		}

		// ensure, that current folder starts with slash and does not end with slash
		if ( currentFolder.length() > 0 ) {
			if ( !currentFolder.startsWith("/") ) {
				currentFolder = "/" + currentFolder;
			}
			if ( currentFolder.endsWith("/") ) {
				currentFolder = currentFolder.substring(0, currentFolder.length() - 1);
			}
		}

		// get all action pages, which exist in current folder

		StringFilter uriFilter = new StringFilter("page.uri");
		uriFilter.createFirstClause(FilterConditions.STRING_STARTS_WITH, currentFolder + "/");

		Grid apGrid = getGridByName(WebappConstants.ACTION_PAGES_GRID, request.getSession());
		if ( apGrid == null ) {
			apGrid = new Grid(WebappConstants.ACTION_PAGES_GRID);
		}

		apGrid.addFilter(uriFilter);

		saveGrid(apGrid, request.getSession());

		QueryInfo queryInfo = new QueryInfo();
		queryInfo.setWhereClause(apGrid.getWhereClause());

		Map queryParameters = new HashMap();
		Locale locale = (Locale) request.getSession().getAttribute(Globals.LOCALE_KEY);
		queryParameters.put("localeIdentifier", locale.getLanguage());
		queryInfo.setQueryParameters(queryParameters);

		PageManager pageManager = (PageManager) getBean(Constants.PAGE_MANAGER_BEAN);
		PartialCollection actionPages = pageManager.listActionPages(queryInfo);

		// we have list of action pages which are all placed in current folder
		// we only need to divide acquired set to subfolders and pages
		// we need regular expression in order to do it:
		String folderPatternString = "";
		if ( currentFolder.length() > 0 ) {
			folderPatternString = "(" + RegExUtil.escapeMetasymbols(currentFolder) + ")";
		}
		folderPatternString += "\\/([^\\/]+)(\\/[^\\/]+)+";

		// pattern compiler instance to use
		PatternCompiler compiler = new Perl5Compiler();

		// compiled patterns
		Pattern folderPattern = compiler.compile(folderPatternString);

		// pattern matcher instance to use
		PatternMatcher matcher = new Perl5Matcher();

		// list of folders
		SortedSet folderSet = new TreeSet();

		// list of pages
		List pages = new ArrayList();

		// list of page urls without locale suffix (for displaying)
		Map urls = new HashMap();

		for ( Iterator i = actionPages.iterator(); i.hasNext(); ) {
			ActionPage actionPage = (ActionPage) i.next();
			String uri = actionPage.getUri();

			// check folder name
			if ( matcher.matches(uri, folderPattern) ) {
				MatchResult result = matcher.getMatch();

				// according to pattern, if current folder is not an empty string, folder name is in second group
				// otherwise it is in the first group;
				String folderName = currentFolder.length() > 0 ? result.group(2) : result.group(1);
				Folder folder = new VirtualFolder(folderName, currentFolder, '/');
				folderSet.add(folder);

			} else {
				// add page to list
				ActionPage tmp = new ActionPage();
				WebappUtil.copyProperties(tmp, actionPage, request);
				tmp.setUri(WebappUtil.getActionMappingURL(uri, null, request, WebappConstants.URL_TYPE_CONTEXT_RELATIVE));
                String url = WebappUtil.getActionMappingURL(uri, null, request, WebappConstants.URL_TYPE_CONTEXT_RELATIVE, false);
                if (url != null) {
                    int lastIndex = url.lastIndexOf('/');
                    if (lastIndex != -1) {
                        url = url.substring(lastIndex + 1);
                    }
                }
				urls.put(actionPage.getId(), url);
				pages.add(tmp);
			}
		}

		// create parent folder if current folder is not the root folder
		Folder parentFolder = null;
		if ( currentFolder.length() > 0 ) {
			int k = currentFolder.lastIndexOf("/");
			if ( k < 0 ) {
				k = 0;
			}
			String parentFolderPath = currentFolder.substring(0, k);
			parentFolder = new VirtualFolder("..", parentFolderPath, '/', true);
		}

		LinkedList folders = new LinkedList(folderSet);

		if ( parentFolder != null ) {
			folders.addFirst(parentFolder);
		}

		request.setAttribute(WebappConstants.ACTION_PAGES_COLLECTION_KEY, pages);
		request.setAttribute(WebappConstants.ACTION_PAGE_URLS_COLLECTION_KEY, urls);
		request.setAttribute(WebappConstants.FOLDERS_COLLECTION_KEY, folders);
		request.setAttribute(WebappConstants.CURRENT_PATH_KEY, new FolderList(VirtualFolder.splitPath(currentFolder)));

		// save transaction token in request
		saveToken(request);
		return mapping.findForward("listActionPages");
	}
}